<template>
  <a-modal
    :title="$t('重新设定密码')"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    :okText="$t('确定')"
    @cancel="handleCancel"
    :cancelText="$t('关闭')"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :label="$t('用户账号')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input :placeholder="$t('请输入用户账号')" v-decorator="['username', {}]" :readOnly="true" />
        </a-form-item>
        <a-form-item :label="$t('登录密码')" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <div style="display: flex; align-items: center; height: 40px">
            <a-input
              type="password"
              :placeholder="$t('请输入登录密码')"
              v-decorator="['password', validatorRules.password]"
            /><!-- <span
              v-if="!freePass"
              style="color: #1890ff; white-space: nowrap; margin-left: 4px"
              @click="closeValid"
              >{{ $t('关闭安全密码') }}</span
            > -->
          </div>
        </a-form-item>
        <a-form-item :label="$t('确认密码')" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
          <a-input
            type="password"
            @blur="handleConfirmBlur"
            :placeholder="$t('请重新输入登录密码')"
            v-decorator="['confirmpassword', validatorRules.confirmpassword]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <yarn-cert-out-captcha-modal
      ref="yarnModal"
      @ok="handleSubmitCallback"
      @cancel="handleSubmitClose"
    ></yarn-cert-out-captcha-modal>
    <user-settings-modal ref="modalForm" @close="modalFormOk" />
  </a-modal>
</template>

<script>
import { changePassword } from '@/api/api'
import YarnCertOutCaptchaModal from '@/views/setting/modules/YarnCertOutCaptchaModal'
import UserSettingsModal from './UserSettingsModal'
export default {
  name: 'PasswordModal',
  components: {
    YarnCertOutCaptchaModal,
    UserSettingsModal,
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      confirmDirty: false,
      validatorRules: {
        password: {
          rules: [{ required: true, message: this.$t('密码不能为空') }, { validator: this.validateToNextPassword }],
        },
        confirmpassword: {
          rules: [
            { required: true, message: this.$t('请重新输入登录密码') },
            { validator: this.compareToFirstPassword },
          ],
        },
      },

      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      freePass: localStorage.getItem('freePass') == 'true' ? true : false,
    }
  },
  methods: {
    closeValid() {
      this.$refs.modalForm.show()
    },
    modalFormOk() {
      this.$nextTick(() => {
        this.freePass = localStorage.getItem('freePass') == 'true' ? true : false
        this.form.validateFields(['password'], { force: true })
      })
    },
    show(username) {
      this.form.resetFields()
      this.visible = true
      this.model.username = username
      this.freePass = localStorage.getItem('freePass') == 'true' ? true : false
      this.$nextTick(() => {
        this.form.setFieldsValue({ username: username })
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.selectedRole = []
    },
    handleSubmit() {
      let that = this
      that.$delete(that.model, 'captcha');
      // 触发表单验证
      that.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(that.model, values)
          changePassword(formData).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
                that.confirmLoading = false
              } else if(res.code == 750){ // 需要验证码
                //认证
                that.$refs.yarnModal.show(formData)
              } else {
                that.$message.warning(res.message)
                that.confirmLoading = false
              }
            })
        }
      })
    },
    handleSubmitCallback(formData) {
      let that = this
      changePassword(formData)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok')
            that.$refs.yarnModal.close()
            that.close()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    handleSubmitClose() {
      this.confirmLoading = false
    },
    handleCancel() {
      this.close()
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      const confirmpassword = form.getFieldValue('confirmpassword')
      if (value && confirmpassword && value !== confirmpassword) {
        callback(this.$t('两次输入的密码不一样'))
      }
      if (!this.freePass) {
        if (!/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,20}$/.test(value)) {
          callback(this.$t('密码由8~20位数字、大小写字母和特殊符号组成!'))
        }
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback(this.$t('两次输入的密码不一样'))
      } else {
        callback()
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
  },
}
</script>